/**
 * QAAgent Java 类示例
 * 
 * 使用前请确保：
 * 1. 已编译 Rust 动态库（libqa_ffi.dylib 或 libqa_ffi.so）
 * 2. 将动态库路径添加到 java.library.path
 */
public class QAAgent {
    private long nativePtr;

    // 加载动态库
    static {
        try {
            System.loadLibrary("qa_ffi");
        } catch (UnsatisfiedLinkError e) {
            System.err.println("无法加载 qa_ffi 动态库: " + e.getMessage());
            System.err.println("请确保动态库在 java.library.path 中");
            throw e;
        }
    }

    // 原生方法声明
    private native long nativeNew(String workspace);
    private native void nativeAnswer(long ptr, String query, LLModel model, AgentResponseStream stream);
    private native void nativeFree(long ptr);

    /**
     * 构造函数
     * 
     * @param workspace workspace 路径字符串
     */
    public QAAgent(String workspace) {
        this.nativePtr = nativeNew(workspace);
        if (this.nativePtr == 0) {
            throw new RuntimeException("Failed to create QAAgent");
        }
    }

    /**
     * 处理用户查询
     * 
     * @param query 用户查询字符串
     * @param model 大模型接口实现
     * @param stream 响应流接口实现
     */
    public void answer(String query, LLModel model, AgentResponseStream stream) {
        if (nativePtr == 0) {
            throw new IllegalStateException("QAAgent has been closed");
        }
        nativeAnswer(this.nativePtr, query, model, stream);
    }

    /**
     * 清理资源
     * 注意：请务必在使用完毕后调用此方法释放资源
     * 推荐使用 try-with-resources 模式或 try-finally 确保资源被释放
     */
    public void close() {
        if (nativePtr != 0) {
            nativeFree(nativePtr);
            nativePtr = 0;
        }
    }
}

